#include "head.h"

int main(int argc, char *argv[])
{
    // 绑定ip和端口
    char ip[100] = {0};
    load_config("ip", ip);
    char port[100] = {0};
    load_config("port", port);

    int socket_fd = socket(AF_INET, SOCK_STREAM, 0);

    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(port));
    addr.sin_addr.s_addr = inet_addr(ip);

    connect(socket_fd, (struct sockaddr *)&addr, sizeof(addr));

    // 初始化请求报文
    request_t *req = (request_t* )malloc(sizeof(request_t));
    memset(req, 0, sizeof(request_t));
    response_t *res = (response_t* )malloc(sizeof(response_t));
    memset(res, 0, sizeof(response_t));
    // 是否已经登录
    int is_login = 0;

    // 拼接登录报文
    req->flag = LOGIN;
    strcpy(req->user_name, argv[1]);

    // 发送login报文
    int ret = send(socket_fd, req, sizeof(request_t), 0);
    // 等待响应报文
    recv(socket_fd, res, sizeof(response_t), 0);
    if (res->status == 0)
    {
        // 修改登录标记位, 避免重复登陆
        is_login = 1;
    }
    printf("%s\n",res->args);
    while (is_login == 1)
    {
        printf("client>");
        fflush(stdout);
        // 到这是正式开始输入命令, req.user_name一直是登陆时的不变了

        // 读标准输入
        char buf[1024] = {0};
        read(STDIN_FILENO, buf, sizeof(buf));
        printf("buf : %s\n", buf);
        // 进行命令分析->拼接报文->发送报文
        int ret = analyze_cmd(socket_fd, buf, req);
        if (ret == -1)
        {
            printf("服务器响应错误\n");
            // break;
            continue;
        }
        if (ret == 1)
        {
            printf("非法命令, 请重新输入.\n");
            continue;
        }
        if (ret == 2)
        {
            // 退出
            break;
        }
    }

    close(socket_fd);
    return 0;
}